<template>
  <a-modal
    v-model:visible="enclosureModal"
    ok-text="创建"
    :on-before-ok="enclosureSubmit"
    @cancel="cancel"
  >
    <template #title> 创建附函 </template>
    <div class="content">
      <a-form ref="enclosureFormRef" :model="enclosureForm">
        <a-row :gutter="12">
          <a-col :span="24">
            <a-form-item
              field="title"
              label="标题"
              :rules="[{ required: true, message: '请输入标题' }]"
              :validate-trigger="['change', 'input']"
            >
              <a-input
                v-model="enclosureForm.title"
                placeholder="请输入"
                :max-length="20"
                show-word-limit
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="12">
          <a-col :span="24">
            <a-form-item
              field="receivers"
              label="收件人"
              :rules="[{ required: true, message: '请选择收件人' }]"
            >
              <UserSelector
                v-model="enclosureForm.receivers"
                placeholder="请输入姓名、角色、公司或电子邮件地址"
                :projectId="projectId"
                multiple
                @change="receiversSelect"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider />
        <a-row :gutter="12">
          <a-col :span="24">
            <div class="title">
              <div class="text">
                <img
                  src="@/assets/images/check/Frame@2x.png"
                  alt=""
                  style="width: 17px; height: 17px"
                />
                <span class="text-font">需附函文件</span>
              </div>
              <div class="file-count">
                <span>总计：{{ fileCounts || 0 }} 个文件</span>
                <a-button
                  v-if="openType == 'enclosure'"
                  type="text"
                  @click="addFileVisible = true"
                >
                  添加文件
                </a-button>
              </div>
            </div>
            <div class="file-list-wrap">
              <FileCollapse :files="enclosureForm.fileList"></FileCollapse>
            </div>
          </a-col>
        </a-row>
        <a-form-item field="message" label="消息" style="margin-top: 20px">
          <a-textarea
            v-model="enclosureForm.message"
            placeholder="请输入"
            :max-length="500"
            show-word-limit
            :auto-size="{
              minRows: 2,
            }"
          />
        </a-form-item>
      </a-form>
      <TreeFolder
        v-model:visible="addFileVisible"
        :ok-function="fileChange"
        :config="{ type: 1 }"
      ></TreeFolder>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { useRoute } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import {
    computed,
    defineEmits,
    defineProps,
    ref,
    reactive,
    watch,
    onMounted,
  } from 'vue';
  import FileCollapse from '@/views/check/components/file-collapse/index.vue';
  import UserSelector from '@/components/user-selector/index.vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import TreeFolder from '@/components/tree-folder/index.vue';
  import { storeToRefs } from 'pinia';
  import useFileManageStore from '@/store/modules/file-manage/index';
  import { getDirectoryFileInfo, attachSaveFun } from '../api';

  const store = useFileManageStore();
  const { enclosureModal, enclosureInfo } = storeToRefs(store);

  const props = defineProps({
    openType: {
      type: String,
    },
  });
  onMounted(() => {
    watch(enclosureInfo, () => {
      console.log(enclosureInfo.value);
    });
  });

  interface enclosureFormInter {
    title: string; // 标题
    receivers: string; // 收件人
    fileList: Array<object>;
    message: string; // 消息
  }
  const enclosureForm = reactive<enclosureFormInter>({
    title: '', // 标题
    receivers: '', // 收件人
    fileList: [],
    message: '', // 消息
  });
  const route = useRoute();
  const projectId = ref(route.params.projectId || '');

  const receiversID = ref([]);
  const addFileVisible = ref(false);
  const fileIds = ref<Array<string>>();
  const enclosureFormRef = ref<FormInstance>();
  const emits = defineEmits(['update:visible', 'refresh']);
  const cancel = () => {
    enclosureFormRef.value?.resetFields();
    emits('update:visible', false);
    store.setEnclosureModal(false, {});
  };
  const fileCounts = computed(() => {
    let counts = 0;
    enclosureForm.fileList?.forEach((file) => {
      const { total } = getDirectoryFileInfo(file);
      counts += total;
    });
    return counts;
  });
  const enclosureSubmit = async (done: any) => {
    const res = await enclosureFormRef.value?.validate();

    if (!fileIds.value) {
      Message.info('请选择文件');
      return;
    }
    if (!res) {
      // const { projectId }: any = route.params;
      const params: any = {
        projectId: projectId.value,
        title: enclosureForm.title,
        message: enclosureForm.message,
        receivers: receiversID.value,
        fileIds: fileIds.value,
      };

      const saveRes = await attachSaveFun(params);
      if (saveRes.status) {
        Message.success('创建成功');
        emits('refresh');
        cancel();
      } else {
        Message.error(saveRes.message);
      }
      done();
    }
  };
  const receiversSelect = (user: any) => {
    receiversID.value = user.map((item: any) => item.id);
  };
  const fileChange = async (data: () => Promise<any>) => {
    const files = await data();
    enclosureForm.fileList = files;
    console.log(enclosureForm.fileList);

    enclosureForm.fileList?.forEach((file) => {
      const { fileIDList } = getDirectoryFileInfo(file);
      fileIds.value = fileIDList;
    });
  };
</script>

<style scoped lang="less">
  .title {
    position: relative;
    .text {
      display: flex;
      align-content: center;
      align-items: center;
    }
    .text-font {
      display: inline-block;
      font-size: 16px;
      font-weight: 600;
      margin-left: 8px;
    }
    .file-count {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
  .file-list-wrap {
    margin-top: 16px;
  }
</style>
